//
//  SRIDCardGenerator.m
//  SunriseReaderDemo
//
//  Created by 田宇 on 2024/11/27.
//  Copyright © 2024 Chenfan. All rights reserved.
//

#import "SRIDCardGenerator.h"

#define IDCardTitleColor  [UIColor colorWithRed:67/255.0 green:142/255.0 blue:219/255.0 alpha:1]

#define IDCardTextColor [UIColor blackColor]

#define padding 10

#define Voffset 5.f
@implementation SRIDCardGenerator

+(UIImage *)generateIDCardFrontImageWithIDCarModel:(SRIDCardModel *)model{
    
    if (!model) {
        NSLog(@"数据为空");
        return nil;
    }
    //身份证正面底图
    UIImage *image = [UIImage imageNamed:@"front"];
    
    CGSize imageSize = image.size;
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
       
    // 绘制身份证照片（底图）
    [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    
    //设置标题样式
    NSDictionary *titleAttributes = @{
        NSFontAttributeName: [UIFont boldSystemFontOfSize:16],
        NSForegroundColorAttributeName: IDCardTitleColor
    };
    //设置文本内容样式
    NSDictionary *textAttributes = @{
        NSFontAttributeName: [UIFont boldSystemFontOfSize:22], // 文本大小
        NSForegroundColorAttributeName: IDCardTextColor // 文本颜色
    };
    
    CGFloat vertical = 40;
    CGFloat titleWidth = 60.f;
    CGFloat titleHeight = 20.f;
    CGRect titleRect =  CGRectMake(40, 60, titleWidth, titleHeight);
    [@"姓  名" drawInRect:titleRect withAttributes:titleAttributes];
    CGRect nameTextRect = CGRectMake(titleRect.origin.x + titleRect.size.width + padding, titleRect.origin.y - Voffset, imageSize.width - titleRect.origin.x + titleRect.size.width, 40);
    [model.name drawInRect:nameTextRect withAttributes:textAttributes];
    
    CGRect genderTitleRect = [self _getNextVerticalOriginalRect:titleRect
                                                     vertical:vertical];
    [@"性  别" drawInRect:genderTitleRect withAttributes:titleAttributes];
    CGRect genderTextRect = [self _getNextVerticalOriginalRect:nameTextRect vertical:vertical];
    genderTextRect.size.width = 60;
    [model.gender drawInRect:genderTextRect withAttributes:textAttributes];

    CGRect nationTitleRect = [self _getTextRectWithTitleRect:genderTitleRect maxWidth:titleWidth xOffset:60.f];
    [@"民  族" drawInRect:nationTitleRect withAttributes:titleAttributes];
    [model.nation drawInRect:[self _getTextRectWithTitleRect:nationTitleRect maxWidth:100] withAttributes:textAttributes];
    
    CGRect birthdayTitleRect = [self _getNextVerticalOriginalRect:genderTitleRect
                                                     vertical:vertical];
    CGRect birthdayTextRect = [self _getNextVerticalOriginalRect:genderTextRect vertical:vertical];
    birthdayTextRect.size.width = 10;
    [@"出  生" drawInRect:birthdayTitleRect withAttributes:titleAttributes];
    [model.year drawInRect:[self _getTextRectWithTitleRect:birthdayTextRect maxWidth:60 xOffset:-20.f]  withAttributes:textAttributes];
    [@"年" drawInRect:[self _getTextRectWithTitleRect:birthdayTitleRect maxWidth:20 xOffset:60.f]  withAttributes:titleAttributes];
    [model.mon drawInRect:[self _getTextRectWithTitleRect:birthdayTextRect maxWidth:40 xOffset:60.f]  withAttributes:textAttributes];
    
    [@"月" drawInRect:[self _getTextRectWithTitleRect:birthdayTitleRect maxWidth:20 xOffset:110.f]  withAttributes:titleAttributes];
    [model.day drawInRect:[self _getTextRectWithTitleRect:birthdayTextRect maxWidth:40 xOffset:120.f]  withAttributes:textAttributes];
    
    [@"日" drawInRect:[self _getTextRectWithTitleRect:birthdayTitleRect maxWidth:20 xOffset:170.f] withAttributes:titleAttributes];
    
    CGRect addressTitleRect = [self _getNextVerticalOriginalRect:birthdayTitleRect vertical:vertical];
    CGRect addressTextRect = [self _getNextVerticalOriginalRect:birthdayTextRect vertical:vertical];
    [@"地  址" drawInRect:addressTitleRect withAttributes:titleAttributes];
    
    CGSize maxSize = CGSizeMake(image.size.width / 2.f, CGFLOAT_MAX); // 最大宽度为绘制区域宽度，高度无限
    CGRect textRect = [model.address boundingRectWithSize:maxSize
                                              options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine
                                           attributes:textAttributes
                                            context:nil];
    
        // 修正绘制区域
    addressTextRect.size.height = textRect.size.height;
    addressTextRect.size.width = textRect.size.width;
    [model.address drawInRect:addressTextRect withAttributes:textAttributes];
    
    
    CGRect IDNumberTitleRect = [self _getNextVerticalOriginalRect:addressTitleRect vertical:100];
    IDNumberTitleRect.size.width = 120;
    [@"公民身份号码" drawInRect:IDNumberTitleRect withAttributes:titleAttributes];
    
    [model.idNum drawInRect:[self _getTextRectWithTitleRect:IDNumberTitleRect maxWidth:imageSize.width] withAttributes:textAttributes];
    
//    绘制头像
    NSData *imageData = [[NSData alloc] initWithBase64EncodedString:model.photo options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *photoImage = [UIImage imageWithData:imageData];
    photoImage = [self removeWhiteBackgroundFromImage:photoImage withThreshold:60
    ];
    [photoImage drawInRect:CGRectMake(image.size.width - 160, 60, photoImage.size.width*1.2, photoImage.size.height *1.2)];
    // 获取合成后的图像
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
       
    // 结束图形上下文
    UIGraphicsEndImageContext();
       
    return resultImage;
    
}


+ (UIImage *)generateIDCardBackImageWithIDCarModel:(SRIDCardModel *)model{
    if (!model) {
        NSLog(@"数据为空");
        return nil;
    }
        //身份证底图
        UIImage *image = [UIImage imageNamed:@"back"];
        
        CGSize imageSize = image.size;
        
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    
        [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
        
        UIImage *guohuiImg = [UIImage imageNamed:@"guohui"];
        CGRect guohuiRect = CGRectMake(0, 20, 200, 140);
        [guohuiImg drawInRect:guohuiRect];
        
        CGRect rect = CGRectMake(guohuiRect.origin.x + guohuiRect.size.width + 80, guohuiRect.origin.y, imageSize.width/3*2.f, 40);
        
    NSDictionary *attributes1 = @{
        NSKernAttributeName: @9,  // 设置字间距，适当增大字间距（单位是点）
        NSForegroundColorAttributeName: IDCardTextColor,
        NSFontAttributeName: [UIFont boldSystemFontOfSize:40],  // 设置字体大小
            NSParagraphStyleAttributeName: [self justifiedParagraphStyle]  // 设置段落样式
        };
        
    [@"中华人民共和国" drawInRect:CGRectMake(160, rect.origin.y + 10, 350, 60) withAttributes:attributes1];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.alignment = NSTextAlignmentJustified;  // 设置为两端对齐
        paragraphStyle.lineSpacing = 8;  // 设置行间距，值越大行间隔越大
    
    NSDictionary *attributes2 = @{
        NSKernAttributeName: @24,  // 设置字间距，适当增大字间距（单位是点）
        NSForegroundColorAttributeName: IDCardTextColor,
        NSFontAttributeName: [UIFont boldSystemFontOfSize:50],  // 设置字体大小
            NSParagraphStyleAttributeName: [self justifiedParagraphStyle]  // 设置段落样式
        };
    
    
     [@"居民身份证" drawInRect:CGRectMake(150, 100, 360, 70) withAttributes:attributes2];
     
    NSDictionary *titleAttributes = @{
        NSForegroundColorAttributeName: IDCardTextColor,
        NSFontAttributeName: [UIFont boldSystemFontOfSize:18],  // 设置字体大小
        };
    
    NSDictionary *textAttributes = @{
        NSForegroundColorAttributeName: IDCardTextColor,
        NSFontAttributeName: [UIFont systemFontOfSize:18],  // 设置字体大小
        };
    
    [@"签发机关" drawInRect:CGRectMake(100, 240, 100, 20) withAttributes:titleAttributes];
    [model.issueOrg drawInRect:CGRectMake(200, 240, 200, 20) withAttributes:textAttributes];
    
    [@"有效期限" drawInRect:CGRectMake(100, 280, 100, 20) withAttributes:titleAttributes];
    
    NSString *date = [NSString stringWithFormat:@"%@-%@",model.effectDate,model.expireDate];
    
    [date drawInRect:CGRectMake(200, 280, 200, 20) withAttributes:textAttributes];
    
     UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    
    return  resultImage;
    
}


+ (UIImage *)generateIDCardImageWithIDCarModel:(SRIDCardModel *)model{
    if (!model) {
        return nil;
    }
    UIImage *image1 = [self generateIDCardFrontImageWithIDCarModel:model];
    UIImage *image2 = [self generateIDCardBackImageWithIDCarModel:model];
    return  [self combineImage:image1 withImage:image2];
    
}

+ (UIImage *)combineImage:(UIImage *)image1 withImage:(UIImage *)image2 {
    // 获取两张图片的尺寸
    CGSize size1 = image1.size;
    CGSize size2 = image2.size;
    
    // 确定合成图片的尺寸，可以根据你的需求进行调整
    CGFloat width = MAX(size1.width, size2.width);
    CGFloat height = size1.height + size2.height;
    CGSize combinedSize = CGSizeMake(width, height);
    
    // 创建一个新的图形上下文
    UIGraphicsBeginImageContextWithOptions(combinedSize, NO, 0.0);
    
    // 将第一个图片绘制到上下文中，绘制的位置是(0, 0)
    [image1 drawInRect:CGRectMake(0, 0, size1.width, size1.height)];
    
    // 将第二个图片绘制到上下文中，绘制的位置是紧接着第一个图片的下方
    [image2 drawInRect:CGRectMake(0, size1.height + 20, size2.width, size2.height)];
    
    // 从上下文中获取合成后的图片
    UIImage *combinedImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 结束图形上下文
    UIGraphicsEndImageContext();
    
    return combinedImage;
}


#pragma mark -- 私有方法_计算位置
+ (CGRect)_getNextVerticalOriginalRect:(CGRect)originalRect
                          vertical:(CGFloat)vertical{
    return  CGRectMake(originalRect.origin.x, originalRect.origin.y + vertical, originalRect.size.width, originalRect.size.height);
}

+ (CGRect)_getTextRectWithTitleRect:(CGRect)titleRect maxWidth:(CGFloat)width{
    return CGRectMake(titleRect.origin.x + titleRect.size.width + padding, titleRect.origin.y - Voffset, width, 40);
}

+ (CGRect)_getTextRectWithTitleRect:(CGRect)titleRect maxWidth:(CGFloat)width xOffset:(CGFloat)xOffset{
    return CGRectMake(titleRect.origin.x + titleRect.size.width + padding + xOffset, titleRect.origin.y, width, 40);
}


//删除白色背景 接近白色，5的阈值
+ (UIImage *)removeWhiteBackgroundFromImage:(UIImage *)image withThreshold:(NSInteger)threshold{
    CGImageRef cgImage = image.CGImage;
    size_t width = CGImageGetWidth(cgImage);
    size_t height = CGImageGetHeight(cgImage);
    
    // 创建一个位图上下文
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 width,
                                                 height,
                                                 8,  // bits per component
                                                 width * 4,  // bytes per row
                                                 CGColorSpaceCreateDeviceRGB(),
                                                 kCGImageAlphaPremultipliedLast);
    
    // 将图片绘制到上下文中
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage);
    
    // 获取位图数据
    unsigned char *data = CGBitmapContextGetData(context);
    
    // 遍历每个像素，删除白色背景
    for (size_t y = 0; y < height; y++) {
        for (size_t x = 0; x < width; x++) {
            // 每个像素的起始位置
            int pixelIndex = ((width * y) + x) * 4;
            
            // 获取RGBA值
            unsigned char red = data[pixelIndex];
            unsigned char green = data[pixelIndex + 1];
            unsigned char blue = data[pixelIndex + 2];
            unsigned char alpha = data[pixelIndex + 3];
            
            // 判断是否接近白色：红、绿、蓝通道的值与255的差值小于等于阈值
                        if (abs(red - 255) <= threshold && abs(green - 255) <= threshold && abs(blue - 255) <= threshold) {
                            data[pixelIndex + 3] = 0;  // 设置透明
                        }
        }
    }
    
    // 创建一个新的CGImage
    CGImageRef newCgImage = CGBitmapContextCreateImage(context);
    
    // 将其转为UIImage
    UIImage *newImage = [UIImage imageWithCGImage:newCgImage];
    
    // 释放上下文和CGImage
    CGContextRelease(context);
    CGImageRelease(newCgImage);
    
    return newImage;
}

//两端对齐样式
+ (NSParagraphStyle *)justifiedParagraphStyle {
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentJustified;  // 设置为两端对齐
    style.lineSpacing = 5;  // 可以根据需要调整行间距
    return style;
}
@end
